package cc.ucanuup.service.base.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cc.ucanuup.common.support.easyui.inter.EasyuiQuery;
import cc.ucanuup.common.support.easyui.view.EasyuiPage;
import cc.ucanuup.service.base.dao.UpUserJPA;
import cc.ucanuup.service.base.dto.UserDto;
import cc.ucanuup.service.base.entity.UpUser;
import cc.ucanuup.service.base.inter.UpUserService;

/**
 * Description: TODO[描述该类概要功能介绍]
 *
 * @author guwenbin
 * @date 2018年2月1日
 * @version 1.0
 */
@Service
@Transactional
public class UpUserServiceImpl implements UpUserService{

	@Autowired
	private UpUserJPA upUserJPA;
	@Autowired
	private UpUserService upUserService;

	@Override
	public UpUser findSupplierByName(String userName) {

		return upUserJPA.findSupplierByName(userName);
	}

	@Override
	public UpUser save(UpUser entity) {

		return upUserJPA.save(entity);
	}

	@Override
	public EasyuiPage<UserDto> queryUserDtoAndSortIt(EasyuiQuery bzPage, String queryMsg) throws Exception  {

		Page<UpUser> page = upUserService.queryUsersAndSortIt(bzPage, queryMsg);
		List<UserDto> list = new ArrayList<UserDto>();
		UserDto dto = null;
		for(UpUser u :page.getContent()){
			dto = new UserDto();
			dto.setId(u.getId());
			dto.setPassword(u.getUserPassword());
			dto.setUserAccount(u.getUserAccount());
			dto.setUserName(u.getSupplierName());
			list.add(dto);
		}
		return new EasyuiPage<UserDto>(list,page.getTotalElements(),page.getNumber()+1);
	}

	@Override
	public Page<UpUser> queryUsersAndSortIt(EasyuiQuery bzPage,final String queryMsg) throws Exception {
		Pageable pageable= new PageRequest(bzPage.getPageNo(), bzPage.getPageSize());
		return upUserJPA.findAll(new Specification<UpUser>() {
			@Override
			public Predicate toPredicate(Root<UpUser> root,CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate userAccount = criteriaBuilder.like(root.get("userAccount").as(String.class),"%"+queryMsg == null? "":queryMsg+"%");
				return criteriaBuilder.and(userAccount);
			}
		},pageable);
	}

	@Override
	public UpUser findSupplierByUserId(String userId) {

		return upUserJPA.findOne(userId);
	}

}
